
from flask import Flask,request,Response,redirect,url_for,render_template_string, abort,session
import json
from werkzeug.utils import secure_filename
import os
import time

app = Flask("my-app", static_folder="path1", template_folder="path2")

@app.route('/')
def hello_world():
    return request.args.__str__()


# 可以处理来自非浏览器的client的请求
# register()函数里无需定义参数
@app.route('/register', methods=['POST'])
def register():
    print(request.headers)
    # print(request.stream.read()) # 不要用，否则下面的form取不到数据
    print(request.form)
    print(request.form['name'])
    print(request.form.get('name'))
    print(request.form.getlist('name'))
    print(request.form.get('nickname', default='little apple'))
    return 'welcome'

@app.route('/add', methods=['POST'])
def add():
    result = {'sum': request.json['a'] + request.json['b']}
    resp = Response(json.dumps(result),  mimetype='application/json')
    resp.headers.add('Server', 'python flask')
    return resp


# 文件上传目录
app.config['UPLOAD_FOLDER'] = 'static/upload/'
# 支持的文件格式
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'}  # 集合类型

# 判断文件名是否是我们支持的格式
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

@app.route('/upload', methods=['POST'])
def upload():
    upload_file = request.files['image']
    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        # 将文件保存到 static/uploads 目录，文件名同上传时使用的文件名
        upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
        return 'info is '+request.form.get('info', '')+'. success'
    else:
        return 'failed'

# redirect函数用于重定向
@app.route('/test1')
def test1():
    print('this is test1')
    return redirect(url_for('test2'))


@app.route('/test2')
def test2():
    print('this is test12')
    return 'this is test22'     # 浏览器显示

# 在浏览器中访问http://127.0.0.1:5001/test1，浏览器的url会变成http://127.0.0.1:5000/test2
# 没有/test3，输入提示Not Found
# Not Found
# The requested URL was not found on the server.
# If you entered the URL manually please check your spelling and try again.


# app.secret_key = 'F12Zr47j\3yX R~X@H!jLwf/T'                      # 用于加密
#
#
# @app.route('/login')
# def login():
#     page = '''
#     <form action="{{ url_for('do_login') }}" method="post">                # 点击提交，就请求do_login方法
#         <p>name: <input type="text" name="user_name" /></p>
#         <input type="submit" value="Submit" />
#     </form>
#     '''
#     return render_template_string(page)
#
#
# @app.route('/do_login', methods=['POST'])
# def do_login():
#     name = request.form.get('user_name')
#     session['user_name'] = name
#     return 'success'
#
#
# @app.route('/show')
# def show():
#     return session['user_name']
#
#
# @app.route('/logout')
# def logout():
#     session.pop('user_name', None)                              # 如果登出了，那么在/show就看不到user_name了，有报错
#     return redirect(url_for('login'))


# 第一次请求没有，第二次请求就有了
@app.route('/add')
def login():
    res = Response('add cookies')
    res.set_cookie(key='name', value='letian', expires=time.time() + 6 * 60)
    return res


@app.route('/show')
def show():
    return request.cookies.__str__()

# 以后也一直有，除非删除掉
@app.route('/del')
def del_cookie():
    res = Response('delete cookies')
    res.set_cookie('name', '', expires=0)
    return res


if __name__ == '__main__':
    app.run(port=5000, debug=True)
